package com.golte.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.github.pagehelper.util.StringUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.commons.codec.binary.StringUtils;

import java.io.Serializable;

/**
 * @Author: sm
 * @Date: 2021/3/6
 * 统一返回格式
 */

@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class GlobalResponse<T> implements Serializable {
    private static final long serialVersionUID = -2281542169281891417L;

    private String msg;

    private String code;

    private T data;

    public GlobalResponse(ResponsesCodeMsg response) {
        this.msg = response.getMsg();
        this.code = response.getCode();
    }

    public GlobalResponse(String code, String msg) {
        this.msg = msg;
        this.code = code;
    }

    public static GlobalResponse ok() {
        GlobalResponse rsp = new GlobalResponse(ResponsesCodeMsg.SUCCESS);
        return rsp;
    }

    @JsonIgnore
    public Boolean isSuccess() {
        if (StringUtils.equals(this.code, ResponsesCodeMsg.SUCCESS.getCode())) {
            return true;
        }
        return false;
    }

    public static <T> GlobalResponse ok(T data) {
        GlobalResponse rsp = new GlobalResponse(ResponsesCodeMsg.SUCCESS);
        rsp.setData(data);
        return rsp;

    }

    public static GlobalResponse fail(String msg) {
        GlobalResponse rsp = new GlobalResponse(ResponsesCodeMsg.ERROR);
        rsp.setMsg(msg);
        return rsp;
    }

    @Override
    public String toString() {
        return "GlobalResponse{" +
                "msg='" + msg + '\'' +
                ", code='" + code + '\'' +
                ", data=" + data +
                '}';
    }

}
